package com.taptech.doufu.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.taptech.doufu.R;
import com.taptech.doufu.net.retrofit.api.RxJavaHelper;
import com.taptech.doufu.ui.activity.base.DiaobaoBaseActivity;
import com.taptech.doufu.ui.adapter.SectionNovelListAdapter;
import com.taptech.doufu.bean.NovelSectionListBean;
import com.taptech.doufu.constant.Constant;
import com.taptech.doufu.listener.HttpResponseListener;
import com.taptech.doufu.services.HomeMainServices;
import com.taptech.doufu.util.TTLog;
import com.taptech.doufu.util.TextUtil;
import com.taptech.doufu.util.UIUtil;
import com.taptech.doufu.net.httputils.HttpResponseObject;
import com.taptech.doufu.weex.module.TFCacheModule;
import com.taptech.doufu.ui.view.PullToRefreshListView;
import com.taptech.doufu.ui.view.WaitDialog;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

public class NovelDesToDetailActivity extends DiaobaoBaseActivity implements View.OnClickListener, HttpResponseListener, AdapterView.OnItemClickListener {
    public static final String ARTICLEID = "articleId";
    public static final String CATELOG = "catelog";
    public static final String INTENT_OFFLINE_LIST = "offline_list";
    public static final String INTENT_OFFLINE_FLAG = "offline_flag";
    public static final String INTENT_CURR_POS = "curr_pos";
    public static final String INTENT_IS_ACTIVITY_FOR_RESULT = "is_activity_for_result";
    private TextView mListNumTv;
    private PullToRefreshListView mNovelListView;
    private SectionNovelListAdapter adapter;
    private String articleId;
    private LinearLayout nullContentTip;
    // 顺序选择
    SharedPreferences sharedPreferences;
    SharedPreferences.Editor sharedPreferencesEditor;
    private final String SHAREDPREFERENCES_NAME = "read_section_sharedpreference";
    private final String SECTION_ORDER_KEY = "read_section_order_key";
    private String sectionOrder = "0";
    private LinearLayout mChooseOrderBtn;
    private TextView mChooseOrderText;
    private ImageView mChooseOrderImg;
    private List<NovelSectionListBean> offLineList;

    private WaitDialog dialog;
    private int currPos;




    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_novel_des_to_detail);

        dialog = new WaitDialog(this, R.style.updateDialog);

        mListNumTv = (TextView) findViewById(R.id.novel_list_num);
        mNovelListView = (PullToRefreshListView) findViewById(R.id.tttalv_novel_object_content);
        mNovelListView.setOnItemClickListener(this);
        nullContentTip = (LinearLayout) findViewById(R.id.novel_comment_tip);
        try {
            articleId = getIntent().getExtras().getString(ARTICLEID);
        } catch (Exception e) {
            e.printStackTrace();
        }
        boolean offlineFlag = getIntent().getBooleanExtra(INTENT_OFFLINE_FLAG, false);

        if (offlineFlag) {
            loadOffLineData();
        }else{
            loadWebData();
        }
    }

    /**
     * 加在离线数据
     */
    private void loadOffLineData() {
        //离线数据
        final String offlineKey = getIntent().getStringExtra(NovelSectionDetailsActivity.INTENT_KEY_OFFLINE_BOOK_KEY);
        if (TextUtil.isEmpty(offlineKey)) {
            loadWebData();
            return;
        }
        TTLog.sout("小说目录==离线");
        Observable.create(new Observable.OnSubscribe<String>() {
            @Override
            public void call(Subscriber<? super String> subscriber) {
                String offline = TFCacheModule.getValue(offlineKey).toString();
                subscriber.onNext(offline);
            }
        }).compose(RxJavaHelper.<String>observeOnMainThread(this))
                .subscribe(new Action1<String>() {
                    @Override
                    public void call(String offline) {
                        try {
                            JSONObject offlineJson = new JSONObject(offline);
                            JSONArray catelogArray = offlineJson.getJSONArray("catelog");
                            offLineList = new ArrayList<>();
                            offLineList.addAll(JSON.parseArray(catelogArray.toString(), NovelSectionListBean.class));
                            if (offLineList != null && offLineList.size() > 0) {
                                initData();
                                initOrderChooseBtn();
                                if (!"0".equals(sectionOrder)){
                                    Collections.reverse(offLineList);
                                }
                                adapter = new SectionNovelListAdapter(NovelDesToDetailActivity.this, articleId);
                                mNovelListView.setAdapter(adapter);
                                mNovelListView.setLoadmoreable(true);
                                setListData(offLineList);
                            }else{
                                loadWebData();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                            loadWebData();
                        }
                    }
                });
    }


    /**
     * 直接获取服务器数据
     */
    private void loadWebData() {
        TTLog.sout("小说目录==在线");
        initData();
        initOrderChooseBtn();
        adapter = new SectionNovelListAdapter(this, articleId);
        mNovelListView.setAdapter(adapter);
        mNovelListView.setLoadmoreable(true);
        //在线
        HomeMainServices.getInstance().loadNovelSectionListNew(NovelDesToDetailActivity.this, articleId, sectionOrder);
    }

    private void initData() {
        if (articleId != null && !articleId.equals("")){
            sharedPreferences = getSharedPreferences(SHAREDPREFERENCES_NAME, MODE_PRIVATE);
            sharedPreferencesEditor = sharedPreferences.edit();
            // 获取章节排列顺序
            sectionOrder = sharedPreferences.getString(SECTION_ORDER_KEY + articleId, "0");
            currPos = getIntent().getIntExtra(INTENT_CURR_POS, -1);
        }
    }

    private void initOrderChooseBtn(){
        mChooseOrderBtn = (LinearLayout) findViewById(R.id.choose_section_order);
        mChooseOrderBtn.setOnClickListener(this);
        mChooseOrderText = (TextView) findViewById(R.id.section_order_text);
        mChooseOrderImg = (ImageView) findViewById(R.id.section_order_img);
        if (sectionOrder != null){
            if (sectionOrder.equals("0")){
                mChooseOrderText.setText("正序");
                mChooseOrderImg.setImageResource(R.drawable.btn_chapter_inverted_xhdpi);
            }else if (sectionOrder.equals("3")){
                mChooseOrderText.setText("倒序");
                mChooseOrderImg.setImageResource(R.drawable.btn_chapter_positive_xhdpi);
            }
        }
    }

    @Override
    public void handleResponse(int handleType, HttpResponseObject response) {
        try {
            if (dialog != null && dialog.isShowing()) {
                dialog.cancel();
            }
            switch (handleType) {
                case HomeMainServices.HANDLE_TYPE_LOAD_SECTION_NOVEL:
                    if (response.getStatus() == 0) {
                        try {
                            JSONObject jsonObject = (JSONObject) response.getData();
                            getObjectDate(jsonObject);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else {
                        mListNumTv.setText("目录");
                        nullContentTip.setVisibility(View.VISIBLE);
                        mNovelListView.getFootView().setVisibility(View.GONE);
                        UIUtil.toastMessage(this, Constant.loadingFail);
                    }
                    break;
                default:
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void topback(View view) {
        onBackPressed();
    }

    private void getObjectDate(JSONObject jsonObject) {
        List<NovelSectionListBean> mainList = null;
        try {
            // main
            mainList = new ArrayList<>();
            JSONArray mainArray = jsonObject.getJSONArray("list");
            mainList.addAll(JSON.parseArray(mainArray.toString(), NovelSectionListBean.class));
            setListData(mainList);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void setListData(List<NovelSectionListBean> mainList) {
        mNovelListView.requestLayout();
        mNovelListView.setEnabled(false);
        // 显示数据
        adapter.clear();
        adapter.setListDate(mainList);
        mListNumTv.setText("总共" + mainList.size() + "章");
        mNovelListView.setFull(true);
        mNovelListView.loadMoreComplete();
        mNovelListView.setEnabled(true);
        setSelection();
    }

    private void setSelection() {
        if (adapter == null) {
            return;
        }
        if (adapter.mainList == null) {
            return;
        }
        if (adapter.mainList.size() <= currPos){
            return;
        }
        if (currPos < 0 ) {
            return;
        }
        mNovelListView.post(new Runnable() {
            @Override
            public void run() {
                if ("3".equals(sectionOrder)) {  //倒序
                    int size = adapter.mainList.size();
                    mNovelListView.setSelection(size - currPos);
                }else{  //正序
                    mNovelListView.setSelection(currPos);
                }
            }
        });



    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.choose_section_order:
                if (dialog != null && !dialog.isShowing()) {
                    dialog.show();
                    if (sectionOrder.equals("0")) {
                        sectionOrder = "3";
                    } else if (sectionOrder.equals("3")) {
                        sectionOrder = "0";
                    }
                    if (sharedPreferencesEditor != null && articleId != null && !articleId.equals("")) {
                        sharedPreferencesEditor.putString(SECTION_ORDER_KEY + articleId, sectionOrder);
                        sharedPreferencesEditor.commit();
                    }
                    if (sectionOrder != null){
                        if (sectionOrder.equals("0")){
                            mChooseOrderText.setText("正序");
                            mChooseOrderImg.setImageResource(R.drawable.btn_chapter_inverted_xhdpi);
                        }else if (sectionOrder.equals("3")){
                            mChooseOrderText.setText("倒序");
                            mChooseOrderImg.setImageResource(R.drawable.btn_chapter_positive_xhdpi);
                        }
                    }
                    loadRefreshSectionData();
                }
                break;
        }
    }

    private void loadRefreshSectionData() {
        mNovelListView.setFull(false);
        mNovelListView.loadMoreView();
        if (offLineList != null && offLineList.size() > 0) {
            if (dialog != null && dialog.isShowing()) {
                dialog.cancel();
            }
            Collections.reverse(offLineList);
            setListData(offLineList);
        }else{
            HomeMainServices.getInstance().loadNovelSectionListNew(NovelDesToDetailActivity.this, articleId, sectionOrder);
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        NovelSectionListBean bean=adapter.getBean(position-1);
        if(bean!=null){
            adapter.setHirstory(bean.getId());
            adapter.notifyDataSetChanged();
            Intent intent=new Intent(this, NovelSectionDetailsActivity.class);
            intent.putExtra(Constant.ARTICLE_ID, bean.getId());// details id
            intent.putExtra(Constant.ARTICLE_NOVELID, adapter.getNovelId());//topic id
            intent.putExtra(Constant.TITLE, bean.getTitle());
            intent.putExtra(Constant.FROM, "NovelDesToDetailActivity");
            if (getIntent().getBooleanExtra(INTENT_IS_ACTIVITY_FOR_RESULT, false)) {
                setResult(RESULT_OK,intent);
            }else{
                startActivity(intent);
            }
            adapter.stopActivity();
        }
    }


    public static void startActivity(Context context, int novelId) {
        Intent intent = new Intent(context, NovelDesToDetailActivity.class);
        intent.putExtra(NovelDesToDetailActivity.ARTICLEID, String.valueOf(novelId));
        context.startActivity(intent);
    }
}
